<?php
namespace app\utils;
class ImgCrop{
	private $file;
    private $image;
    private $width;
    private $height;
    private $bits;
    private $mime;

	public function __construct($file){
		if (!file_exists($file))
            throw new \Exception('Error: Could not load image ' . $file . '!');
        $this->file = $file;

		if(class_exists('Imagick')){
			$this->image = new \Imagick($file);
		}else if (!extension_loaded('gd')) {
            throw new \Exception('Error: PHP GD is not installed!');
        }else{
        	$this->image = new GdImgPick($file);
        }

        $info = getimagesize($file);

        $this->width = $info[0];
        $this->height = $info[1];
        $this->bits = isset($info['bits']) ? $info['bits'] : '';
        $this->mime = isset($info['mime']) ? $info['mime'] : '';
	}
	public function cropImage($targetFile, $width, $height=''){
		$className = get_class($this->image);
		if($className == 'Imagick'){
			return $this->imagickCrop($targetFile, $width, $height);			
		}else if(stripos($className, 'GdImgPick')!==false){
			return $this->image->cropImage($targetFile, $width, $height);
		}
		return false;
	}
	public function waterImage($waterFile, $position=''){
		$className = get_class($this->image);
		if($className == 'Imagick'){
			return $this->imagickAddWater($waterFile, $position);
		}else if(stripos($className, 'GdImgPick')!==false){
			$watermark = new GdImgPick($waterFile);
			$this->image->watermark($watermark, $position);
			$this->image->save();
			return true;
		}
		return false;
	}
	public function imagickCrop($targetFile, $width, $height){
		$info = pathinfo($this->file);
		$extension = strtolower($info['extension']);
		$image = $this->image;
		// 裁剪图片
		$startX = intval($width / 2);
		$startY = $height <=0 ? 0 : intval($height / 2);

		try {
			if((($startX + $width) > $this->width) ||
			(($startY + $height) > $this->height)
    		){
				$image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS,1);
    		}else{
    			$image->cropImage($width, $height, $startX, $startY);
				// 设置图像格式以去除额外的元数据，防止文件过大或损坏
				$image->setImageFormat($extension); // 根据需要更改格式，如'png', 'gif'等
				$image->setImagePage($width, $height, 0, 0); // 重设图像大小和偏移量
    		}   			
			
			// 保存裁剪后的图片
			$image->writeImage($targetFile); // 根据需要更改格式，如'png', 'gif'等
			 
			// 销毁Imagick对象以释放内存
			$image->clear();
			$image->destroy();
			return true;
		} catch (\Exception $e) {
			// 销毁Imagick对象以释放内存
			$image->clear();
			$image->destroy();
			return false;
		}
	}
	public function imagickAddWater($waterFile, $position='', $opacity=0.5){
		$watermark = new \Imagick($waterFile);
		if($watermark->getImageWidth() > $this->width || $watermark->getImageHeight() > $this->height ){
            $watermark->resizeImage(ceil($this->width/2), ceil($this->height/2),\Imagick::FILTER_LANCZOS,1);
        }
        //透明
        $watermark->evaluateImage(\Imagick::EVALUATE_MULTIPLY, (1 - $opacity), \Imagick::CHANNEL_ALPHA);
		$image = $this->image;
		switch ($position) {
			case 'all':
                // 計算重複覆蓋的行和列數
                $repeatRows = ceil($this->height / $watermark->getImageWidth());
                $repeatCols = ceil($this->width / $watermark->getImageHeight());
                for ($row = 0; $row < $repeatRows; $row++) {
                    for ($col = 0; $col < $repeatCols; $col++) {
                        // 計算當前位置
                        $x = $col * $watermark->getImageWidth();
                        $y = $row * $watermark->getImageHeight();
                        // 複製水印到目標圖片的位置
                        $image->compositeImage($watermark, \Imagick::COMPOSITE_OVER, $x, $y);
                    }
                }
                break;
            case 'topleft':
                $watermark_pos_x = 0;
                $watermark_pos_y = 0;
                break;
            case 'topcenter':
                $watermark_pos_x = intval(($this->width - $watermark->getImageWidth()) / 2);
                $watermark_pos_y = 0;
                break;
            case 'topright':
                $watermark_pos_x = $this->width - $watermark->getImageWidth();
                $watermark_pos_y = 0;
                break;
            case 'middleleft':
                $watermark_pos_x = 0;
                $watermark_pos_y = intval(($this->height - $watermark->getImageHeight()) / 2);
                break;
            case 'middlecenter':
                $watermark_pos_x = intval(($this->width - $watermark->getImageWidth()) / 2);
                $watermark_pos_y = intval(($this->height - $watermark->getImageHeight()) / 2);
                break;
            case 'middleright':
                $watermark_pos_x = $this->width - $watermark->getImageWidth();
                $watermark_pos_y = intval(($this->height - $watermark->getImageHeight()) / 2);
                break;
            case 'bottomleft':
                $watermark_pos_x = 0;
                $watermark_pos_y = $this->height - $watermark->getImageHeight();
                break;
            case 'bottomcenter':
                $watermark_pos_x = intval(($this->width - $watermark->getImageWidth()) / 2);
                $watermark_pos_y = $this->height - $watermark->getImageHeight();
                break;
            case 'bottomright':
            default:
                $watermark_pos_x = $this->width - $watermark->getImageWidth();
                $watermark_pos_y = $this->height - $watermark->getImageHeight();
                break;
        }
        if($position != 'all'){
        	// 合成水印到原始图片上           
			$image->compositeImage($watermark, \Imagick::COMPOSITE_OVER, $watermark_pos_x, $watermark_pos_y);
		}
		// 保存结果到新文件或覆盖原文件
		$image->writeImage($this->file);
		// 销毁Imagick对象释放内存
		$image->clear();
		$image->destroy();
		$watermark->clear();
		$watermark->destroy();
		return true;
	}
}
